package jp.eisbahn.mgapi.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.eisbahn.mgapi.auth.AuthorizationCodeListener;

/**
 * This servlet class has an ability to receive an authorization code.
 * @author Yoichiro Tanaka
 */
@SuppressWarnings("serial")
public class AuthorizationCodeServlet extends HttpServlet {

    /** The parameter name of an authorization code. */
    private static final String AUTHORIZATION_CODE_PARAM_NAME = "code";
    /** The parameter name of an error message. */
    public static final String ERROR_PARAM_NAME = "error";

    /** The lisneter object to notify an authorization code. */
    private AuthorizationCodeListener authorizationCodeListener;

    /*
     * (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(
     * javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected final void doGet(final HttpServletRequest req,
            final HttpServletResponse resp)
            throws ServletException, IOException {
        String authorizationCode =
            req.getParameter(AUTHORIZATION_CODE_PARAM_NAME);
        if (authorizationCode != null) {
            authorizationCodeListener.set(authorizationCode);
            return;
        }
        String error = req.getParameter(ERROR_PARAM_NAME);
        if (error != null) {
            authorizationCodeListener.error(error);
            return;
        }
        throw new ServletException("Both code and error parameters not found.");
    }

    /**
     * Set the listener object.
     * @param newAuthorizationCodeListener The listener object.
     */
    public final void setAuthorizationCodeListener(
            final AuthorizationCodeListener newAuthorizationCodeListener) {
        authorizationCodeListener = newAuthorizationCodeListener;
    }

    /**
     * Retrieve the listener object.
     * @return The listener object.
     */
    public final AuthorizationCodeListener getAuthorizationCodeListener() {
        return authorizationCodeListener;
    }

}
